package com.example.pilipili.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.pilipili.common.R;
import com.example.pilipili.pojo.dto.CommentDto;
import com.example.pilipili.pojo.entity.Comment;
import com.example.pilipili.dao.CommentMapper;
import com.example.pilipili.service.CommentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyv
 * @since 2023-12-01
 */
@Service
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    CommentMapper commentMapper ;


    @Override
    public R<List<CommentDto>> getsByVid(int vid) {


        // 获取所有父评论
        List<CommentDto> commentDtos = commentMapper.getsParent(vid) ;
        for (CommentDto item :commentDtos){
            List<CommentDto> list = new ArrayList<>() ;
            // 子一级评论
            List<CommentDto> childs = commentMapper.selectListByVP(vid,item.getId()) ;

            for (CommentDto child : childs) {
                child.setPname(item.getUName());
                list.add(child) ;
                // 子n级评论
                recursively(child.getId(),child.getUName(),vid,list);
            }
            item.setChild(list);
        }

        return R.ok(commentDtos);
    }

    private void recursively(int pid, String pname , int vid ,List<CommentDto> list){
        List<CommentDto> childs = commentMapper.selectListByVP(vid,pid) ;
        if(childs.size() > 0) {
            for (CommentDto child : childs){
                child.setPname(pname);
                list.add(child);
                recursively(child.getId(),child.getUName(),vid,list);
            }
        }
    }

    @Override
    public R del(int cid) {
        QueryWrapper<Comment> qw = new QueryWrapper<>() ;
        qw.eq("id",cid) ;
        commentMapper.delete(qw) ;
        return R.ok();
    }

    @Override
    public R<Comment> ban(int cid) {
        Comment comment = commentMapper.selectById(cid) ;
        if(comment == null) {
            return R.failed("不存在");
        }
        comment.setStatus(1);
        comment.setContent("该评论涉嫌违规内容，已被折叠");
        commentMapper.updateById(comment) ;

        return R.ok(comment);
    }

    @Override
    public R<Comment> add(Comment entry) {
        entry.setTime(LocalDate.now());
        commentMapper.insert(entry);
        return R.ok(entry);
    }
}
